<template>
  <!-- vp-raw的作用是隔绝vitepress样式对当前组件的样式影响 -->
  <div class="vp-raw">
    <vxe-grid v-bind="gridOptions" @edit-disabled="editDisabledEvent" @valid-error="onValidateError" ref="VXETableRef">
      <template #name_edit="scope">
        <vxe-input v-model="scope.row.name" @change="() => onChange(scope)"></vxe-input>
      </template>
      <template #sex_edit="{ row }">
        <vxe-input v-model="row.sex"></vxe-input>
      </template>
      <template #age_edit="{ row }">
        <vxe-input v-model="row.age"></vxe-input>
      </template>
      <template #address_edit="{ row }">
        <vxe-input v-model="row.address"></vxe-input>
      </template>
    </vxe-grid>
    <a-button type="primary" @click="onValidateFull">校验整个表格的数据</a-button>
    <div>
      {{ gridOptions.data }}
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'

const VXETableRef = ref()
const gridOptions = reactive({
  border: true,
  showOverflow: true,
  editConfig: {
    trigger: 'click',
    mode: 'row',
    // 返回true表示可编辑, false表示不可编辑
    beforeEditMethod({ rowIndex }) {
      if (rowIndex === 1) {
        return false
      }
      return true
    },
  },
  columns: [
    { type: 'seq', width: 50 },
    { field: 'name', title: '名字', editRender: {}, slots: { edit: 'name_edit' } },
    { field: 'sex', title: '性别', editRender: {}, slots: { edit: 'sex_edit' } },
    { field: 'age', title: '年龄', editRender: {}, slots: { edit: 'age_edit' } },
    { field: 'address', title: '地址', editRender: {}, slots: { edit: 'address_edit' } },
  ],
  /**
   * 数据校验规则
   */
  editRules: {
    name: [
      { required: true, message: '请输入名称', trigger: 'change' },
      { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'change' },
    ],
    age: [{ required: true, message: '请输入年龄', trigger: 'change' }],
  },
  data: [
    { id: 10001, name: 'Test1', nickname: 'T1', role: 'Develop', sex: 'Man', age: 28, address: 'Shenzhen' },
    { id: 10002, name: 'Test2', nickname: 'T2', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
    { id: 10003, name: 'Test3', nickname: 'T3', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
    { id: 10004, name: 'Test4', nickname: 'T4', role: 'Designer', sex: 'Women', age: 23, address: 'Shenzhen' },
    { id: 10005, name: 'Test5', nickname: 'T5', role: 'Develop', sex: 'Women', age: 30, address: 'Shanghai' },
  ],
})
function onChange(scope) {
  const vxeTableInstance = VXETableRef.value
  if (!vxeTableInstance) return

  vxeTableInstance.updateStatus(scope)
}
const editDisabledEvent = () => {
  console.log('禁止编辑')
}
function onValidateError() {
  console.log('onValidateError')
}
async function onValidateFull() {
  // 每次只会校验一个单元格中的数据
  const ret = await VXETableRef.value.fullValidate(true)
  console.log('ret', ret)
}
</script>
